<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card v-loading="isLoading" class="tree-card">
        <!-- 用了一个行列布局 -->
        <el-row type="flex" justify="space-between" align="middle" style="height: 40px">
          <el-col :span="20">
            <span>{{ company.manager }}</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex">
              <!-- 两个内容 -->
              <el-col :span="12">{{ company.manager }}</el-col>
              <el-col :span="12">
                <!-- 下拉菜单 element -->
                <el-dropdown>
                  <span> 操作<i class="el-icon-arrow-down" /> </span>
                  <!-- 下拉菜单 -->
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="addDepts(company)"
                      >添加子部门</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-tree :data="departs" :props="defaultProps">
          <template v-slot:default="{ data }">
            <!-- 使用 scoped slot 会传入两个参数node和data，分别表示当前节点的 Node 对象和当前节点的数据。 -->
            <el-row
              type="flex"
              justify="space-between"
              align="middle"
              style="height: 40px; width: 100%"
            >
              <el-col :span="20">
                <span>{{ data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex">
                  <!-- 两个内容 -->
                  <el-col :span="12">{{ data.manager }}</el-col>
                  <el-col :span="12">
                    <!-- 下拉菜单 element -->
                    <!-- $event表示原来默认的参数 -->
                    <el-dropdown @command="handleClickDepts($event, data)">
                      <span @click.stop> 操作<i class="el-icon-arrow-down" /> </span>
                      <!-- 下拉菜单 -->
                      <el-dropdown-menu slot="dropdown">
                        <!-- @click.native="delDepts" -->
                        <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                        <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                        <el-dropdown-item command="del">删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>
      <!-- sync:表示父组件传给子组件得值，放权给子组件去修改 -->
      <addDepts
        ref="addDepts"
        :show-dialog.sync="showDialog"
        :node-data="nodeData"
        :depart-list="departList"
        @add-success="getDepartmentsList"
      />
    </div>
  </div>
</template>

<script>
import { getDepartmentsListApi, delDepartmentsApi } from '@/api/departments'
import { tansListToTreeData } from '@/utils/index'
import addDepts from './componments/add-depts.vue' // 引入新增部门组件
export default {
  name: 'Departments',
  components: {
    addDepts
  },
  data() {
    return {
      company: {
        name: '',
        manager: '负责人',
        id: '',
        children: []
      },
      departs: [],
      defaultProps: {
        label: 'name'
      },
      showDialog: false,
      nodeData: {},
      departList: [],
      isLoading: false
    }
  },
  async created() {
    this.getDepartmentsList()
  },
  methods: {
    async getDepartmentsList() {
      this.isLoading = true
      const { data } = await getDepartmentsListApi()
      this.company.name = data.companyName
      this.departList = data.depts
      this.departs = tansListToTreeData(data.depts, '')
      this.company.children = this.departs
      this.isLoading = false
      console.log(data)
    },
    handleClickDepts(cmd, data) {
      if (cmd === 'add') {
        // 点击的是添加按钮
        // console.log('点击的是添加按钮')
        this.addDepts(data)
      }
      if (cmd === 'edit') {
        // console.log('点击的是编辑按钮')
        this.editDepts(data)
      }
      if (cmd === 'del') {
        // console.log('点击的是删除按钮')
        this.delDepts(data.id)
      }
    },
    editDepts(data) {
      // 异步
      this.showDialog = true
      this.nodeData = data
      // 调用获取部门负责人接口
      // this.$refs.addDepts.getUserSimpLeList()
      // this.$refs.addDepts.showTitle = '编辑部门'
      this.$nextTick(() => {
        // 说明异步DOM更新完毕了,获取数据详情
        this.$refs.addDepts.getDepartmentDetail()
      })
    },
    delDepts(id) {
      // console.log(id)
      this.$confirm('您确定要删除吗？该操作不可逆哦', '温馨提示')
        .then(async () => {
          // 调接口
          await delDepartmentsApi(id)
          // this.$message({
          //   message: '删除成功',
          //   type: 'success'
          // })
          // 提示框
          this.$message.success('删除成功')
          // 重新渲染
          // 这里不同父组件得数据，所以不需要加$nextTick
          this.getDepartmentsList()
        })
        .catch(() => {})
    },
    /** 添加功能 */
    addDepts(data) {
      this.showDialog = true
      // console.log(data)
      this.nodeData = data
      // this.$refs.addDepts.showTitle = '添加部门'
      // this.$refs.addDepts.getUserSimpLeList()
    },
    closeDialog() {
      this.showDialog = false
    }
    // // 使用递归的方式
    // tansListToTreeData(list, searchVal) {
    //   // 思路：先找父级，找到父级然后根据父级找子集
    //   const arr = []
    //   list.forEach(item => {
    //     if (item.pid === searchVal) {
    //       // 走进if之后，说明找到父级了
    //       // 根据父级找子级
    //       const children = this.tansListToTreeData(list, item.id)
    //       item.children = children
    //       arr.push(item)
    //     }
    //   })
    //   return arr
    // }

    // // 转换平摊数组位树形结构，接收平铺的数组，返回一个属性解构
    // tansListToTreeData(list) {
    //   // 思路：先找父级，找到父级然后根据父级找子集
    //   let arr = []
    //   // 找list中pid为空的数据（也就是父级）
    //   arr = list.filter(item => item.pid === '')
    //   // console.log(arr)
    //   arr.forEach(item => {
    //     // 根据父级找子集，拿父级的id和list中所有子级的pid去对比
    //     const children = list.filter(child => item.id === child.pid) || []
    //     item.children = children
    //   })
    //   return arr
    // }
  }
}
</script>

<style scoped lang="scss">
.el-tree {
  // 样式穿透
  ::v-deep {
    // 小三角的样式, 去掉默认的小三角的旋转效果
    .el-tree-node__expand-icon.expanded {
      -webkit-transform: rotate(0deg);
      transform: rotate(0deg);
    }
    // 有子节点 且未展开 +
    .el-icon-caret-right:before {
      background: url('~@/assets/common/add-circle.png') no-repeat 0 0;
      content: '';
      display: block;
      width: 16px;
      height: 16px;
      font-size: 16px;
      background-size: 16px;
    }
    // 有子节点 且已展开 -
    .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
      background: url('~@/assets/common/minus-circle.png') no-repeat 0 0;
      content: '';
      display: block;
      width: 16px;
      height: 16px;
      font-size: 16px;
      background-size: 16px;
    }
    // 没有子节点
    .el-tree-node__expand-icon.is-leaf::before {
      background: url('~@/assets/common/user-filling.png') no-repeat 0 0;
      content: '';
      display: block;
      width: 16px;
      height: 16px;
      font-size: 16px;
      background-size: 16px;
    }
  }
}
</style>
